package com.xiaoshuidi.cloud.module.iot.task;

import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.iot.dal.model.hikvision.DeletionFaceReqDto;
import com.xiaoshuidi.cloud.module.iot.dal.model.hikvision.HikvisionCommon;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbFaceDatabase;
import com.xiaoshuidi.cloud.module.iot.dal.repository.TbFaceDatabaseRepository;
import com.xiaoshuidi.cloud.module.iot.service.HikvisionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Feng
 * @date 2023/6/28
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class FaceDatabaseTask {

    private final TbFaceDatabaseRepository faceDatabaseRepository;
    private final HikvisionService hikvisionService;

    /**
     * 定时扫描 - 失效过去三天有效到期人脸信息
     */
    @XxlJob("iot-invalidity-face")
    @TenantIgnore
    public void invalidityFace() {
        log.info("--失效过去三天有效到期的人脸信息：开始---");
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.plusDays(-3);
        //批量删除第三方人脸信息
        List<TbFaceDatabase> faceList = faceDatabaseRepository.invalidityFaceList(startDate, endDate);
        Map<String, List<String>> faceGroupMap = faceList.stream().collect(Collectors.groupingBy(TbFaceDatabase::getThirdFaceGroupId,
                Collectors.mapping(TbFaceDatabase::getThirdFaceId, Collectors.toList())));
        faceGroupMap.keySet().forEach(s -> {
            List<String> faceIndexCodeList = faceGroupMap.get(s);
            DeletionFaceReqDto dto = new DeletionFaceReqDto();
            dto.setFaceGroupIndexCode(s);
            dto.setIndexCodes(faceIndexCodeList);
            HikvisionCommon<Boolean> hikvisionCommon = hikvisionService.deletionFace(dto);
            if (HikvisionCommon.SUCCESS_CODE.equals(hikvisionCommon.getCode())) {
                //修改失效
                log.info("删除第三方人脸信息成功");
                int count = faceDatabaseRepository.invalidityFace(startDate, endDate, faceIndexCodeList);
                log.info("--失效过去三天有效到期的人脸信息：结束,共失效{}条---", count);
            } else {
                log.info("删除第三方人脸信息失败: {}", hikvisionCommon.getMsg());
            }
        });
    }
}
